<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--区域数据-->
            <el-col :span="4" :xs="24">
                <div class="box-card">
                    <div class="head-container">
                        <el-input v-model="filterText" placeholder="请输入区域名称" clearable size="small"
                            prefix-icon="el-icon-search" style="margin-bottom: 20px" />
                    </div>
                    <div class="head-container">
                        <el-tree :data="regionList" :props="defaultProps" :expand-on-click-node="false"
                            :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all
                            highlight-current @node-click="handleNodeClick">
                        </el-tree>
                    </div>
                </div>
            </el-col>
            <!--房间数据-->
            <el-col :span="20" :xs="24">
                <el-form :model="queryParamsRoom" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                    label-width="68px">
                    <el-form-item label="房间名称" prop="userName">
                        <el-input v-model="queryParamsRoom.name" placeholder="请输入房间名称" clearable style="width: 240px" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>

                <el-table v-loading="loading" :data="userList" style="width: 100%">
                    <el-table-column prop="name" label="空间名称">
                    </el-table-column>
                    <el-table-column prop="maxNumber" label="最大人数">
                    </el-table-column>
                    <el-table-column prop="roomType" label="房间类型">
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="text" size="small" @click="viewPensonnel(scope.row)">空间成员</el-button>
                            <el-button type="text" size="small" @click="addPersonnel(scope.row)">绑定成员</el-button>
                            <el-button type="text" size="small" @click="addPrograms(scope.row)">绑定模板</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList" />
            </el-col>
        </el-row>



        <el-dialog title="成员列表" :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
            <el-row :gutter="20">
                <!--部门数据-->
                <el-col :span="4" :xs="24">
                    <div class="head-container">
                        <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small"
                            prefix-icon="el-icon-search" style="margin-bottom: 20px" />
                    </div>
                    <div class="head-container">
                        <el-tree :data="deptOptions" :props="defaultPropsUeser" :expand-on-click-node="false"
                            :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all
                            highlight-current @node-click="handleNodeClickUser" />
                    </div>
                </el-col>
                <!--用户数据-->
                <el-col :span="20" :xs="24">


                    <el-table v-loading="loading" ref="multipleTable" :data="userListNew"
                        @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="50" align="center" />
                        <el-table-column label="用户编号" align="center" key="userId" prop="userId" />
                        <el-table-column label="用户名称" align="center" key="userName" prop="userName"
                            :show-overflow-tooltip="true" />
                        <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName"
                            :show-overflow-tooltip="true" />
                        <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName"
                            :show-overflow-tooltip="true" />
                        <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" />
                        <el-table-column label="状态" align="center" key="status">
                        </el-table-column>
                        <el-table-column label="创建时间" align="center" prop="createTime">
                            <template slot-scope="scope">
                                <span>{{ parseTime(scope.row.createTime) }}</span>
                            </template>
                        </el-table-column>
                    </el-table>

                    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize" @pagination="getList" />
                </el-col>
            </el-row>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="getAddBatchIds">确 定</el-button>
            </span>
        </el-dialog>


        <el-dialog title="空间成员列表" :visible.sync="dialogVisiblePersonnel" width="50%" :before-close="handleClose">
            <el-row :gutter="20">
                <!--用户数据-->
                <el-table v-loading="loading" :data="userListNew" style="width: 100%;">
                    <el-table-column label="用户编号" align="center" prop="userId" />
                    <el-table-column label="用户昵称" align="center" prop="sysUser.nickName"
                        :show-overflow-tooltip="true" />
                    <el-table-column label="部门" align="center" prop="deptName" :show-overflow-tooltip="true" />
                    <el-table-column label="最近登录时间" align="center" prop="sysUser.loginDate">
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="text" size="small" @click="delPersonnel(scope.row)">解绑</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="queryPersonnel.total > 0" :total="queryPersonnel.total"
                    :page.sync="queryPersonnel.pageNum" :limit.sync="queryPersonnel.pageSize" />
            </el-row>
        </el-dialog>



        <el-dialog title="模板列表" :visible.sync="dialogVisiblePrograms" width="50%" :before-close="handleClose">
            <el-row :gutter="20">
                <!--用户数据-->
                <el-table :data="programs" style="width: 100%;">
                    <el-table-column label="模板名称" align="center" prop="programName" />
                    <!-- <el-table-column label="模板状态" align="center" prop="programStatus" :show-overflow-tooltip="true" /> -->
                    <el-table-column label="修改时间" align="center" prop="updateTime">
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button type="text" size="small" @click="bangPersonnel(scope.row)">绑定</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="queryPersonnel.total > 0" :total="queryPersonnel.total"
                    :page.sync="queryPersonnel.pageNum" :limit.sync="queryPersonnel.pageSize" />
            </el-row>
        </el-dialog>
    </div>
</template>

<script>
import { listNoPage, addRoom, listRoom, editRoom } from "@/api/region/index";
import { listUser, deptTreeSelect } from "@/api/system/user";
import { addBatchIds, listPersonnel, delper } from "@/api/personnel/index";
import { programList, programIssued, programDeital, programUpdate, deviceDetail } from '@/api/information/index';
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { row } from "mathjs";

export default {
    name: "User",
    dicts: ['sys_normal_disable', 'sys_user_sex'],
    components: { Treeselect },
    data() {
        return {
            selectionTabel: [],
            filterText: '',
            url: process.env.VUE_APP_BASE_API + '/iot/upload',
            header: {
                Authorization: 'Bearer ' + getToken(),
                clientid: process.env.VUE_APP_CLIENT_ID
            },
            dialogVisiblePersonnel: false,
            dialogVisiblePrograms: false,
            drawerRoom: false,
            roomTitle: "新增房间",
            direction: 'rtl',
            drawer: false,
            regionTitle: "添加区域",
            formInline: {
                id: "",
                locationName: ""
            },
            formInlineRoom: {
                id: "",
                name: "",
                roomType: "",
                maxNumber: "",
                regionId: "",
                remarks: "",
                background: "",
                auditName: ""
            },
            deptName: "",
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 用户表格数据
            userList: null,
            // 弹出层标题
            title: "",
            // 部门树选项
            deptOptions: undefined,
            // 是否显示弹出层
            open: false,
            regionList: [],
            // 日期范围
            dateRange: [],
            // 岗位选项
            postOptions: [],
            // 角色选项
            roleOptions: [],
            // 表单参数
            form: {},
            defaultProps: {
                children: "children",
                label: "locationName"
            },
            defaultPropsUeser: {
                children: "children",
                label: "label"
            },
            queryParamsRoom: {
                pageNum: 1,
                pageSize: 10,
                regionId: "",
                name: ""
            },
            userListNew: [],
            queryParamsUser: {
                pageNum: 1,
                pageSize: 10,
                total: 0,
                deptId: ""
            },
            queryPersonnel: {
                pageNum: 1,
                pageSize: 10,
                total: 0,
                roomId: ''
            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10
            },
            deviceInfo: {},
            roomObject: {},
            dialogVisible: false,
            programs: [],
            roomData: {},
            userListSelect: []
        };
    },
    watch: {
        // 根据名称筛选部门树
        filterText(val) {
            this.$refs.tree.filter(val);
        }
    },
    created() {
        this.getList();
        this.getListRoom()
    },
    methods: {
        getprogramList() {
            programList({
                pageNum: 1,
                pageSize: 10,
                programClass: '1829805119231696898',
                programName: '',
                programStatus: ''
            }).then((res) => {
                this.programs = res.rows;
                this.total = res.total
                this.dialogVisiblePrograms = true
            });
        },
        addPrograms(val) {
            deviceDetail(val.deviceId).then(response => {
                this.deviceInfo = response.data
                listPersonnel({
                    pageNum: 1,
                    pageSize: 999,
                    roomId: val.id
                }).then(response => {
                    this.userListNew = response.rows
                    this.getprogramList()
                    this.roomData = val
                });
            });
        },
        bangPersonnel(val) {
            console.log(JSON.parse(val.programData))
            let programData = JSON.parse(val.programData)
            const count = programData.filter(item => item.component === "ManInfo2").length;
            const countMunch = programData.filter(item => item.component === "ManInfo").length;
            if (count == 0 && countMunch == 0) {
                this.$message.error('当前模板没有人员信息框');
                return;
            }
            if (count != 0 && countMunch != 0) {
                this.$message.error('模板配置有错误不支持单人多人混合使用');
                return;
            }
            if (this.userListNew.length > count && countMunch == 0) {
                this.$message.error('当前模板仅支持' + count + "人");
                return;
            }
            this.roomData.programId = val.id
            let macList = []
            macList.push(this.deviceInfo.deviceMac)
            editRoom(this.roomData).then((res) => {
                // 还需做审核处理，生成审核数据
                if (val.programStatus == '2') {
                    if (countMunch == 0) {
                        this.handlingSingle(val, macList)
                    }
                    if (count == 0) {
                        this.handMultiplePeople(val, macList)
                    }
                } else {
                    this.$message.error('请通知管理员审核');
                }
            });
        },
        /**
         * 获取节目详情
         */
        getprogramDeital(id) {
            if (id == null) {
                return;
            }
            programDeital(id).then(response => {
                this.programs = response.data
                // this.userListSelect
            });
        },
        getAddBatchIds() {
            let array = []
            for (let i in this.ids) {
                let object = {
                    roomId: this.roomObject.id,
                    userId: this.ids[i]
                }
                array.push(object)
            }
            addBatchIds(array).then(response => {
                this.dialogVisible = false
                this.ids = []
                programDeital(this.roomObject.programId).then(response => {
                    this.programs = response.data
                    if (this.programs.programStatus != '2') {
                        this.$message.error('添加成功,无法下发模板,当前模板正在审批中');
                        return;
                    }
                    let programData = JSON.parse(this.programs.programData)
                    const count = programData.filter(item => item.component === "ManInfo2").length;
                    const countMunch = programData.filter(item => item.component === "ManInfo").length;

                    if (count == 0 && countMunch == 0) {
                        this.$message.error('添加成功,无法下发模板,当前模板没有人员信息框');
                        return;
                    }

                    if (count != 0 && countMunch != 0) {
                        this.$message.error('添加成功,无法下发模板,模板配置有错误不支持单人多人混合使用');
                        return;
                    }

                    if (this.ids.length > count && countMunch == 0) {
                        this.$message.error('添加成功,无法下发模板,当前模板仅支持' + count + "人");
                        return;
                    }
                    let macList = []
                    macList.push(this.deviceInfo.deviceMac)
                    listPersonnel(this.queryPersonnel).then(response => {
                        console.log(this.userListNew)
                        this.userListNew = response.rows
                        if (countMunch == 0) {
                            this.handlingSingle(this.programs, macList)
                        }
                        if (count == 0) {
                            this.handMultiplePeople(this.programs, macList)
                        }
                    });

                });
                this.$message({
                    message: '添加成功',
                    type: 'success'
                });
            });
        },
        /**
         * 处理单人版本设置
         * @param row 
         */
        handlingSingle(val, macList) {
            let programData = JSON.parse(val.programData)
            // 遍历 programData 并找到 component 为 "ManInfo2" 的对象
            let userIndex = 0;

            for (let i in programData) {
                if (programData[i].component === "ManInfo2") {
                    programData[i].propValue.userList = "";
                }
            }
            for (let i in programData) {
                if (programData[i].component === "ManInfo2" && this.userListNew[userIndex]) {
                    programData[i].propValue.userList = this.userListNew[userIndex].userId;
                    userIndex++;
                }
            }
            val.programData = JSON.stringify(programData);
            programUpdate(val).then((res) => {
                programIssued({
                    id: val.id,
                    macList: macList,
                    type: '2'
                }).then((res) => {
                    // if (res.code == 200) {
                    //     this.$message({
                    //         type: 'success',
                    //         message: '成功!'
                    //     });
                    // }
                    this.dialogVisiblePrograms = false
                });
            });
        },

        /**
         * 处理多人设置
         * @param row 
         */
        handMultiplePeople(val, macList) {
            let programData = JSON.parse(val.programData)
            for (let i in programData) {
                if (programData[i].component === "ManInfo") {
                    programData[i].propValue.userList = []
                    for (let j in this.userListNew) {
                        programData[i].propValue.userList.push(this.userListNew[j].userId)
                    }
                }
            }
            val.programData = JSON.stringify(programData);
            programUpdate(val).then((res) => {
                programIssued({
                    id: val.id,
                    macList: macList,
                    type: '2'
                }).then((res) => {
                    // if (res.code == 200) {
                    //     this.$message({
                    //         type: 'success',
                    //         message: '成功!'
                    //     });
                    // }
                    this.dialogVisiblePrograms = false
                });
            });
        },

        //删除人员信息
        delPersonnel(row) {
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                delper(row.id).then(response => {
                    let programData = JSON.parse(this.programs.programData)
                    const count = programData.filter(item => item.component === "ManInfo2").length;
                    const countMunch = programData.filter(item => item.component === "ManInfo").length;
                    if (this.programs.programStatus != '2') {
                        this.$message.error('解绑成功,无法下发,当前模板正在审批中');
                        this.getlistPersonnel()
                        return;
                    }
                    if (count == 0 && countMunch == 0) {
                        this.$message.error('解绑成功,无法下发,当前模板没有人员信息框');
                        this.getlistPersonnel()
                        return;
                    }

                    if (count != 0 && countMunch != 0) {
                        this.$message.error('解绑成功,无法下发,模板配置有错误不支持单人多人混合使用');
                        this.getlistPersonnel()
                        return;
                    }

                    this.$message({
                        type: 'success',
                        message: '解绑成功!'
                    });
                    let macList = []
                    macList.push(this.deviceInfo.deviceMac)
                    listPersonnel(this.queryPersonnel).then(response => {
                        this.userListNew = response.rows

                        if (countMunch == 0) {
                            this.handlingSingle(this.programs, macList)
                        }
                        if (count == 0) {
                            this.handMultiplePeople(this.programs, macList)
                        }
                    });
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },

        // 更新空间用户查询

        // 查询空间用户
        getlistPersonnel() {
            listPersonnel(this.queryPersonnel).then(response => {
                console.log(this.userListNew)
                this.userListNew = response.rows
                this.queryPersonnel.total = response.total
                this.dialogVisiblePersonnel = true
            });
        },
        viewPensonnel(row) {
            deviceDetail(row.deviceId).then(response => {
                this.deviceInfo = response.data
                this.roomData = row
                if (row.programId != null) {
                    programDeital(row.programId).then(response => {
                        this.programs = response.data
                        this.queryPersonnel.roomId = row.id
                        // this.dialogVisiblePersonnel = true
                        this.getlistPersonnel()
                    });
                } else {
                    this.queryPersonnel.roomId = row.id
                    this.getlistPersonnel()
                }
            });
        },
        handleNodeClickUser(data) {
            this.queryParamsUser.deptId = data.id;
            this.getListUser();
        },
        /** 查询部门下拉树结构 */
        getDeptTree() {
            deptTreeSelect().then(response => {
                this.deptOptions = response.data;
            });
        },
        getListUser(row) {
            listUser(this.queryParamsUser).then(response => {
                this.userListNew = response.rows;
                this.queryParamsUser.total = response.total
                listPersonnel({
                    pageNum: 1,
                    pageSize: 9999,
                    roomId: row.id
                }).then(response => {
                    this.userListSelect = response.rows
                    this.toggleSelection(this.userListNew)
                });
            });
        },
        addPersonnel(row) {
            deviceDetail(row.deviceId).then(response => {
                this.deviceInfo = response.data
                this.roomObject = row
                this.dialogVisible = true
                // this.getprogramDeital(row.programId);
                this.getDeptTree()
                this.getListUser(row)
            });
        },
        onSubmitRoom() {
            addRoom(this.formInlineRoom).then(response => {
                this.$message({
                    message: '添加成功',
                    type: 'success'
                });
                this.drawerRoom = false
                this.formInlineRoom = {
                    id: "",
                    name: "",
                    roomType: "",
                    maxNumber: "",
                    regionId: "",
                    remarks: "",
                    background: "",
                    auditName: ""
                }
            }
            );
        },
        /** 查询区域列表 */
        getList() {
            listNoPage(this.queryParams).then(response => {
                this.regionList = response.data;
            });
        },
        /** 查询房间 */
        getListRoom() {
            this.loading = true
            listRoom(this.queryParamsRoom).then(response => {
                this.userList = response.rows;
                this.total = response.total
                this.loading = false
            });
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                    done();
                })
                .catch(_ => { });
        },
        onSubmit() {
        },
        resetForm() {
        },
        // 筛选节点
        filterNode(value, data) {
            console.log(value, data)
            if (!value) return true;
            return data.locationName.indexOf(value) !== -1;
        },
        // 节点单击事件
        handleNodeClick(data) {
            this.queryParamsRoom.regionId = data.id;
            this.getListRoom();
        },
        // 用户状态修改
        handleStatusChange(row) {
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                userId: undefined,
                deptId: undefined,
                userName: undefined,
                nickName: undefined,
                password: undefined,
                phonenumber: undefined,
                email: undefined,
                sex: undefined,
                status: "0",
                remark: undefined,
                postIds: [],
                roleIds: []
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getListRoom();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.queryParams.deptId = undefined;
            this.$refs.tree.setCurrentKey(null);
            this.handleQuery();
        },
        toggleSelection(rows) {
            // 找出 userListNew 中那些在 userListSelect 里也有相同 id 的对象
            const commonUsers = this.userListNew.filter(newUser => {
                return this.userListSelect.some(selectUser => selectUser.userId === newUser.userId);
            });
            // console.
            commonUsers.forEach(row => {
                this.$refs.multipleTable.toggleRowSelection(row);
            });
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            console.log(selection)
            this.selectionTabel = selection
            this.ids = selection.map(item => item.userId);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        // 更多操作触发
        handleCommand(command, row) {
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.userId != undefined) {
                        updateUser(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addUser(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {

        }
    }
};
</script>

<style scoped>
.demo-form-inline {
    padding: 20px;
}

.btn {
    width: 100%;
    text-align: right;
}

.box-card {
    height: 100vh;
    border-right: 1px solid #eee;
    padding: 10px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 12px;
    padding-right: 8px;
}

.el-tree-node__expand-icon.is-leaf {
    display: none;
}
</style>